package cn.iocoder.yudao.module.alipay.service.alipermission;

import cn.iocoder.yudao.module.alipay.controller.admin.infoauthaliapp.vo.InfoAuthAliAppCreateReqVO;
import cn.iocoder.yudao.module.alipay.dal.dataobject.infoauthaliapp.InfoAuthAliAppDO;
import cn.iocoder.yudao.module.alipay.dal.dataobject.infothirdaliapp.InfoThirdAliAppDO;
import cn.iocoder.yudao.module.alipay.dal.mysql.infoauthaliapp.InfoAuthAliAppMapper;
import cn.iocoder.yudao.module.alipay.dal.mysql.infothirdaliapp.InfoThirdAliAppMapper;
import cn.iocoder.yudao.module.alipay.service.infoauthaliapp.InfoAuthAliAppService;
import cn.iocoder.yudao.module.alipay.util.Tool;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.*;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@Service
@Slf4j
public class AliPayServiceImpl implements AliPayService {


    @Resource
    private InfoAuthAliAppMapper infoAuthAliAppMapper;

    @Resource
    private InfoThirdAliAppMapper infoThirdAliAppMapper;

    private InfoAuthAliAppService infoAuthAliAppService;


    /**
     * (支付宝) 换取授权访问令牌
     * @param grantType 必选 授权方式
     * @param code 可选 授权码
     * @param refreshToken 可选 刷新令牌
     * @return
     */
    @Override
    public Map getAuthToken(String grantType, String code, String refreshToken,String appId) throws AlipayApiException {

        CertAlipayRequest certAlipayRequest = Tool.getRequestTemplate();
        AlipayClient alipayClient = null;
        try {
            alipayClient = new DefaultAlipayClient(certAlipayRequest);
        } catch (AlipayApiException e1) {
            e1.printStackTrace();
        }

        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        // 构建请求参数
        request.setGrantType(grantType);
        request.setCode(code);


        InfoAuthAliAppDO infoAuthAliAppDO = infoAuthAliAppMapper.selectByAppId(appId);
        log.error("appId:{}",appId);
        log.error("app_auth_token:{}",infoAuthAliAppDO.getAppAuthToken());
        request.putOtherTextParam("app_auth_token", infoAuthAliAppDO.getAppAuthToken());
        if(ObjectUtils.isNotEmpty(grantType)){
            request.setGrantType(grantType);
        }else if(ObjectUtils.isNotEmpty(refreshToken)){
            request.setRefreshToken(refreshToken);
        }

        // 响应
        AlipaySystemOauthTokenResponse response = alipayClient.certificateExecute(request);

        System.out.println(response);
        System.out.println(JSON.parseObject(response.getBody()));
        if(response.isSuccess()){
            log.info("[AlipaySystemOauthTokenResponse] >>>> Succeed!");
           // return BeanConvertUtils.objectToMap(JSON.parseObject(response.getBody()));
            return JSON.parseObject(response.getBody());
        } else {
            log.error("[AlipaySystemOauthTokenResponse] = Fail! Cause:{}",response.getSubMsg());
            throw new AlipayApiException("获取支付宝信息失败,请稍后再试!");
        }
    }

    @Override
    public Object createOrder(String buyerId, BigDecimal totalAmount,String outTradeNo,String appId) throws AlipayApiException {
        CertAlipayRequest certAlipayRequest = Tool.getRequestTemplate();
        AlipayClient alipayClient = null;
        try {
            alipayClient = new DefaultAlipayClient(certAlipayRequest);
        } catch (AlipayApiException e1) {
            e1.printStackTrace();
        }
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", outTradeNo);
        bizContent.put("total_amount", 9.9);
        bizContent.put("op_app_id", appId);
        bizContent.put("subject", "宝宝起名字");
        bizContent.put("buyer_id", buyerId);
        bizContent.put("timeout_express", "10m");
        AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
        appId = "2021004133687041";//固定为模板id
        InfoAuthAliAppDO infoAuthAliAppDO = infoAuthAliAppMapper.selectByAppId(appId);
        log.error("app_auth_token:{}",infoAuthAliAppDO.getAppAuthToken());
        request.putOtherTextParam("app_auth_token", infoAuthAliAppDO.getAppAuthToken());
        request.setNotifyUrl("");

        //// 商品明细信息，按需传入
        //JSONArray goodsDetail = new JSONArray();
        //JSONObject goods1 = new JSONObject();
        //goods1.put("goods_id", "goodsNo1");
        //goods1.put("goods_name", "子商品1");
        //goods1.put("quantity", 1);
        //goods1.put("price", 9.9);
        //goodsDetail.add(goods1);
        //bizContent.put("goods_detail", goodsDetail);

        //// 扩展信息，按需传入
        //JSONObject extendParams = new JSONObject();
        //extendParams.put("sys_service_provider_id", "2088511833207846");
        //bizContent.put("extend_params", extendParams);

        //// 结算信息，按需传入
        //JSONObject settleInfo = new JSONObject();
        //JSONArray settleDetailInfos = new JSONArray();
        //JSONObject settleDetail = new JSONObject();
        //settleDetail.put("trans_in_type", "defaultSettle");
        //settleDetail.put("amount", 9.9);
        //settleDetailInfos.add(settleDetail);
        //settleInfo.put("settle_detail_infos", settleDetailInfos);
        //bizContent.put("settle_info", settleInfo);

        //// 二级商户信息，按需传入
        //JSONObject subMerchant = new JSONObject();
        //subMerchant.put("merchant_id", "2088000603999128");
        //bizContent.put("sub_merchant", subMerchant);

        //// 业务参数信息，按需传入
        //JSONObject businessParams = new JSONObject();
        //businessParams.put("busi_params_key", "busiParamsValue");
        //bizContent.put("business_params", businessParams);

        //// 营销信息，按需传入
        //JSONObject promoParams = new JSONObject();
        //promoParams.put("promo_params_key", "promoParamsValue");
        //bizContent.put("promo_params", promoParams);

        request.setBizContent(bizContent.toString());
        AlipayTradeCreateResponse response = alipayClient.certificateExecute(request);
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }
        return JSON.parseObject(response.getBody());
    }

    @Override
    public Map getAppAuthTokenByCode(String grantType, String code) throws AlipayApiException {
        CertAlipayRequest certAlipayRequest = Tool.getRequestTemplate();
        AlipayClient alipayClient = null;
        try {
            alipayClient = new DefaultAlipayClient(certAlipayRequest);
        } catch (AlipayApiException e1) {
            e1.printStackTrace();
        }
        AlipayOpenAuthTokenAppRequest request = new AlipayOpenAuthTokenAppRequest();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        jsonObject.put("grant_type", grantType);//authorization_code或者refresh_token
        request.setBizContent(jsonObject.toString());
        AlipayOpenAuthTokenAppResponse response = alipayClient.certificateExecute(request);
        System.out.println(response);
        System.out.println(JSON.parseObject(response.getBody()));
        if(response.isSuccess()){
            log.info("[AlipaySystemOauthTokenResponse] >>>> Succeed!");
            // return BeanConvertUtils.objectToMap(JSON.parseObject(response.getBody()));
            return JSON.parseObject(response.getBody());
        } else {
            log.error("[AlipaySystemOauthTokenResponse] = Fail! Cause:{}",response.getSubMsg());
            throw new AlipayApiException("获取支付宝信息失败,请稍后再试!");
        }
    }

    @Override
    public Object uploadAppVersion(String authAppId) throws AlipayApiException {

        InfoAuthAliAppDO infoAuthAliAppDO = infoAuthAliAppMapper.selectById(authAppId);

        InfoThirdAliAppDO infoThirdAliAppDO = infoThirdAliAppMapper.selectByAppId(infoAuthAliAppDO.getThirdAppId());

        String appVersion = queryAppVersionList(String.valueOf(infoAuthAliAppDO.getAppId()));
        if(StringUtils.isEmpty(appVersion)){
            appVersion = "0.0.1";
        }else{
            String[] split = appVersion.split("\\.");
            Integer s = Integer.parseInt(split[split.length - 1])+1;
            String newAppVersion = "";
            for (int i = 0; i < split.length; i++) {
                if(i==split.length-1){
                    newAppVersion = newAppVersion + s;
                }else{
                    newAppVersion = newAppVersion+split[i]+".";
                }
            }
            appVersion = newAppVersion;
        }

        CertAlipayRequest certAlipayRequest = Tool.getRequestTemplate();
        AlipayClient alipayClient = null;
        try {
            alipayClient = new DefaultAlipayClient(certAlipayRequest);
        } catch (AlipayApiException e1) {
            e1.printStackTrace();
        }
        // 构造请求参数以调用接口
        AlipayOpenMiniVersionUploadRequest request = new AlipayOpenMiniVersionUploadRequest();
        request.putOtherTextParam("app_auth_token", infoAuthAliAppDO.getAppAuthToken());
        AlipayOpenMiniVersionUploadModel model = new AlipayOpenMiniVersionUploadModel();
        infoAuthAliAppDO.setDevelopmentVersion(appVersion);
        infoAuthAliAppDO.setAppState("待审核");
        infoAuthAliAppDO.setOperateStatue("1");
        // 设置自定义参数
//        model.setExt("{\"extEnable\": true, \"extPages\": {\"pages/face/index\": {\"defaultTitle\": \"哈哈哈哈\"}},\"window\": {\"defaultTitle\": \"AI2\"}}");

        // 设置小程序模板版本号
        //model.setTemplateVersion("0.0.1");

        // 设置商家小程序版本号
        model.setAppVersion(appVersion);
        // 设置小程序投放的端参数
        model.setBundleId("com.alipay.alipaywallet");

        // 设置小程序模板 APPID
        model.setTemplateId(String.valueOf(infoThirdAliAppDO.getTemplateId()));

        request.setBizModel(model);
        AlipayOpenMiniVersionUploadResponse response = alipayClient.certificateExecute(request);
        System.out.println(response.getBody());
        if (response.isSuccess()) {
            infoAuthAliAppMapper.updateById(infoAuthAliAppDO);
            System.out.println("调用成功");
        } else {
            JSONObject jsonObject = JSON.parseObject(response.getBody());
            String alipayOpenMiniVersionListQueryResponse = jsonObject.getString("alipay_open_mini_version_upload_response");
            JSONObject parse = JSON.parseObject(alipayOpenMiniVersionListQueryResponse);
            String subMsg = parse.getString("sub_msg");
            if(subMsg!=null){
                if("存在更大的商家小程序版本号".equals(subMsg)||"请重新输入新的版本号".equals(subMsg)){
                    appVersion = queryAppVersionList(String.valueOf(infoAuthAliAppDO.getAppId()));
                    String[] split = appVersion.split("\\.");
                    Integer s = Integer.parseInt(split[0])+1;
                    split[0] = s+"";
                    String newAppVersion = "";
                    for (int i = 0; i < split.length; i++) {
                        if(i==split.length-1){
                            newAppVersion = newAppVersion + split[i];
                        }else{
                            newAppVersion = newAppVersion+split[i]+".";
                        }
                    }

                    appVersion = newAppVersion;
                }
                // 构造请求参数以调用接口
                infoAuthAliAppDO.setAppState("待审核");
                infoAuthAliAppDO.setOperateStatue("1");
                // 设置商家小程序版本号
                model.setAppVersion(appVersion);

                // 设置小程序投放的端参数
                model.setBundleId("com.alipay.alipaywallet");

                // 设置小程序模板 APPID
                model.setTemplateId(String.valueOf(infoThirdAliAppDO.getTemplateId()));
                request.setBizModel(model);
                response = alipayClient.certificateExecute(request);
                System.out.println(response.getBody());
            }
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
            if (response.isSuccess()) {
                infoAuthAliAppMapper.updateById(infoAuthAliAppDO);
                System.out.println("调用成功");
            } else {
                System.out.println("调用失败");
            }
        }
        return response;
    }

    @Override
    public Object auditAppVersion(String authAppId) throws AlipayApiException {
        InfoAuthAliAppDO infoAuthAliAppDO = infoAuthAliAppMapper.selectById(authAppId);

        InfoThirdAliAppDO infoThirdAliAppDO = infoThirdAliAppMapper.selectByAppId(infoAuthAliAppDO.getThirdAppId());

        String appVersion = queryAppVersionList(String.valueOf(infoAuthAliAppDO.getAppId()));
        System.out.println("调用成功");

        JSONObject jsonObject = queryAppVersionDetail(String.valueOf(infoThirdAliAppDO.getTemplateId()), appVersion);
        String versionDesc = jsonObject.getString("version_desc");
        CertAlipayRequest certAlipayRequest = Tool.getRequestTemplate();
        AlipayClient alipayClient = null;
        try {
            alipayClient = new DefaultAlipayClient(certAlipayRequest);
        } catch (AlipayApiException e1) {
            e1.printStackTrace();
        }
        // 构造请求参数以调用接口
        AlipayOpenMiniVersionAuditApplyRequest request = new AlipayOpenMiniVersionAuditApplyRequest();
        request.putOtherTextParam("app_auth_token", infoAuthAliAppDO.getAppAuthToken());
        infoAuthAliAppDO.setDevelopmentVersion(appVersion);
        infoAuthAliAppDO.setAppState("待上架");
        infoAuthAliAppDO.setOperateStatue("2");
        // 设置审核类型
        request.setAuditRule("BASE_PROMOTE");

        // 设置小程序版本描述
        request.setVersionDesc("优化功能");

        // 设置小程序版本号
        request.setAppVersion(appVersion);

        // 设置区域类型
        request.setRegionType("CHINA");

        // 设置是否加速
        request.setSpeedUp("true");

        AlipayOpenMiniVersionAuditApplyResponse response = alipayClient.certificateExecute(request);
        System.out.println(response.getBody());

        if (response.isSuccess()) {
            infoAuthAliAppMapper.updateById(infoAuthAliAppDO);
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }
        return response;
    }

    @Override
    public Object onlineAppVersion(String authAppId) throws AlipayApiException {
        CertAlipayRequest certAlipayRequest = Tool.getRequestTemplate();
        AlipayClient alipayClient = null;
        try {
            alipayClient = new DefaultAlipayClient(certAlipayRequest);
        } catch (AlipayApiException e1) {
            e1.printStackTrace();
        }
        InfoAuthAliAppDO infoAuthAliAppDO = infoAuthAliAppMapper.selectById(authAppId);

        InfoThirdAliAppDO infoThirdAliAppDO = infoThirdAliAppMapper.selectByAppId(infoAuthAliAppDO.getThirdAppId());

        String appVersion = queryAppVersionList(String.valueOf(infoAuthAliAppDO.getAppId()));


        // 构造请求参数以调用接口
        AlipayOpenMiniVersionOnlineRequest request = new AlipayOpenMiniVersionOnlineRequest();

        request.putOtherTextParam("app_auth_token", infoAuthAliAppDO.getAppAuthToken());
        infoAuthAliAppDO.setOnlineVersion(appVersion);
        infoAuthAliAppDO.setAppState("已上架");
        infoAuthAliAppDO.setOperateStatue("3");
        // 构造请求参数以调用接口
        AlipayOpenMiniVersionOnlineModel model = new AlipayOpenMiniVersionOnlineModel();

        // 设置商家小程序版本号
        model.setAppVersion(appVersion);

        request.setBizModel(model);
        AlipayOpenMiniVersionOnlineResponse response = alipayClient.certificateExecute(request);
        System.out.println(response.getBody());

        if (response.isSuccess()) {
            infoAuthAliAppMapper.updateById(infoAuthAliAppDO);

            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }

        return response;
    }

    @Override
    public Object queryAppVersion(String authAppId) throws AlipayApiException {
        CertAlipayRequest certAlipayRequest = Tool.getRequestTemplate();
        AlipayClient alipayClient = null;
        try {
            alipayClient = new DefaultAlipayClient(certAlipayRequest);
        } catch (AlipayApiException e1) {
            e1.printStackTrace();
        }
        InfoAuthAliAppDO infoAuthAliAppDO = infoAuthAliAppMapper.selectById(authAppId);

        InfoThirdAliAppDO infoThirdAliAppDO = infoThirdAliAppMapper.selectByAppId(infoAuthAliAppDO.getThirdAppId());

        String appVersion = queryAppVersionList(String.valueOf(infoAuthAliAppDO.getAppId()));


        // 构造请求参数以调用接口
        AlipayOpenMiniVersionDetailQueryRequest request = new AlipayOpenMiniVersionDetailQueryRequest();

        request.putOtherTextParam("app_auth_token", infoAuthAliAppDO.getAppAuthToken());

        AlipayOpenMiniVersionDetailQueryModel model = new AlipayOpenMiniVersionDetailQueryModel();

        // 设置小程序版本号
        model.setAppVersion(appVersion);

        // 设置小程序端
        model.setBundleId("com.alipay.alipaywallet");

        request.setBizModel(model);
        AlipayOpenMiniVersionDetailQueryResponse response = alipayClient.certificateExecute(request);
        System.out.println(response.getBody());

        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }


        return response;
    }

    @Override
    public Object delAppVersion(String authAppId) throws AlipayApiException {
        CertAlipayRequest certAlipayRequest = Tool.getRequestTemplate();
        AlipayClient alipayClient = null;
        try {
            alipayClient = new DefaultAlipayClient(certAlipayRequest);
        } catch (AlipayApiException e1) {
            e1.printStackTrace();
        }
        InfoAuthAliAppDO infoAuthAliAppDO = infoAuthAliAppMapper.selectById(authAppId);

        InfoThirdAliAppDO infoThirdAliAppDO = infoThirdAliAppMapper.selectByAppId(infoAuthAliAppDO.getThirdAppId());

        String appVersion = queryAppVersionList(String.valueOf(infoAuthAliAppDO.getAppId()));


        // 构造请求参数以调用接口
        AlipayOpenMiniVersionDeleteRequest  request = new AlipayOpenMiniVersionDeleteRequest();
        request.putOtherTextParam("app_auth_token", infoAuthAliAppDO.getAppAuthToken());
        AlipayOpenMiniVersionDeleteModel model = new AlipayOpenMiniVersionDeleteModel();
        infoAuthAliAppDO.setDevelopmentVersion("");
        infoAuthAliAppDO.setOperateStatue("0");

        // 设置小程序版本号
        model.setAppVersion(appVersion);

        // 设置小程序端
        model.setBundleId("com.alipay.alipaywallet");

        request.setBizModel(model);
        AlipayOpenMiniVersionDeleteResponse response = alipayClient.certificateExecute(request);
        System.out.println(response.getBody());

        if (response.isSuccess()) {
            infoAuthAliAppMapper.updateById(infoAuthAliAppDO);
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }


        return response;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Object cancleAppVersion(String authAppId) throws AlipayApiException {
        CertAlipayRequest certAlipayRequest = Tool.getRequestTemplate();
        AlipayClient alipayClient = null;
        try {
            alipayClient = new DefaultAlipayClient(certAlipayRequest);
        } catch (AlipayApiException e1) {
            e1.printStackTrace();
        }
        InfoAuthAliAppDO infoAuthAliAppDO = infoAuthAliAppMapper.selectById(authAppId);

        InfoThirdAliAppDO infoThirdAliAppDO = infoThirdAliAppMapper.selectByAppId(infoAuthAliAppDO.getThirdAppId());

        String appVersion = queryAppVersionList(String.valueOf(infoAuthAliAppDO.getAppId()));


        // 构造请求参数以调用接口
        AlipayOpenMiniVersionAuditCancelRequest  request = new AlipayOpenMiniVersionAuditCancelRequest();
        request.putOtherTextParam("app_auth_token", infoAuthAliAppDO.getAppAuthToken());
        AlipayOpenMiniVersionAuditCancelModel model = new AlipayOpenMiniVersionAuditCancelModel();
        infoAuthAliAppDO.setDevelopmentVersion("撤回审核");
        infoAuthAliAppDO.setOperateStatue("1");

        // 设置小程序版本号
        model.setAppVersion(appVersion);

        // 设置小程序端
        model.setBundleId("com.alipay.alipaywallet");

        request.setBizModel(model);
        AlipayOpenMiniVersionAuditCancelResponse response = alipayClient.certificateExecute(request);
        System.out.println(response.getBody());
        if (response.isSuccess()) {
            infoAuthAliAppMapper.updateById(infoAuthAliAppDO);
        } else {
            System.out.println("调用失败");
        }
        return response;
    }



    @Override
    public Object offlineAppVersion(String authAppId) throws AlipayApiException {
        CertAlipayRequest certAlipayRequest = Tool.getRequestTemplate();
        AlipayClient alipayClient = null;
        try {
            alipayClient = new DefaultAlipayClient(certAlipayRequest);
        } catch (AlipayApiException e1) {
            e1.printStackTrace();
        }
        InfoAuthAliAppDO infoAuthAliAppDO = infoAuthAliAppMapper.selectById(authAppId);

        InfoThirdAliAppDO infoThirdAliAppDO = infoThirdAliAppMapper.selectByAppId(infoAuthAliAppDO.getThirdAppId());

        String appVersion = queryAppVersionList(String.valueOf(infoAuthAliAppDO.getAppId()));


        // 构造请求参数以调用接口
        AlipayOpenMiniVersionOfflineRequest  request = new AlipayOpenMiniVersionOfflineRequest();
        request.putOtherTextParam("app_auth_token", infoAuthAliAppDO.getAppAuthToken());
        AlipayOpenMiniVersionOfflineModel model = new AlipayOpenMiniVersionOfflineModel();
        infoAuthAliAppDO.setOnlineVersion("");
        infoAuthAliAppDO.setOperateStatue("0");

        // 设置小程序版本号
        model.setAppVersion(appVersion);

        // 设置小程序端
        model.setBundleId("com.alipay.alipaywallet");

        request.setBizModel(model);
        AlipayOpenMiniVersionOfflineResponse response = alipayClient.certificateExecute(request);
        System.out.println(response.getBody());
        if (response.isSuccess()) {
            infoAuthAliAppMapper.updateById(infoAuthAliAppDO);
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }


        return response;
    }

    @Override
    public Object isPassedAppVersion(String authAppId) throws AlipayApiException {
//        CertAlipayRequest certAlipayRequest = Tool.getRequestTemplate();
//        AlipayClient alipayClient = null;
//        try {
//            alipayClient = new DefaultAlipayClient(certAlipayRequest);
//        } catch (AlipayApiException e1) {
//            e1.printStackTrace();
//        }
//        InfoAuthAliAppDO infoAuthAliAppDO = infoAuthAliAppMapper.selectById(authAppId);
//
//        InfoThirdAliAppDO infoThirdAliAppDO = infoThirdAliAppMapper.selectByAppId(infoAuthAliAppDO.getThirdAppId());
//
//        String appVersion = queryAppVersionList(String.valueOf(infoAuthAliAppDO.getAppId()));
//
//        if(StringUtils.isEmpty(appVersion)){
//            appVersion = "0.0.1";
//        }else{
//            String[] split = appVersion.split("\\.");
//            Integer s = Integer.parseInt(split[split.length - 1])+1;
//            String newAppVersion = "";
//            for (int i = 0; i < split.length; i++) {
//                if(i==split.length-1){
//                    newAppVersion = newAppVersion + s;
//                }else{
//                    newAppVersion = newAppVersion+split[i]+".";
//                }
//            }
//            appVersion = newAppVersion;
//        }
//        // 构造请求参数以调用接口
//        AlipayOpenMiniVersionAuditPassedRequest  request = new AlipayOpenMiniVersionAuditPassedRequest();
//        request.putOtherTextParam("app_auth_token", infoAuthAliAppDO.getAppAuthToken());
//        AlipayOpenMiniVersionOfflineModel model = new AlipayOpenMiniVersionOfflineModel();
//        infoAuthAliAppDO.setOnlineVersion("");
//        infoAuthAliAppDO.setOperateStatue("0");
//        infoAuthAliAppMapper.updateById(infoAuthAliAppDO);
//
//        // 设置小程序版本号
//        model.setAppVersion(appVersion);
//
//        // 设置小程序端
//        model.setBundleId("com.alipay.alipaywallet");
//
//        request.setBizModel(model);
//        AlipayOpenMiniVersionOfflineResponse response = alipayClient.certificateExecute(request);
//        System.out.println(response.getBody());
//        if (response.isSuccess()) {
//            System.out.println("调用成功");
//        } else {
//            System.out.println("调用失败");
//        }
//

        return null;
    }

    @Override
    public Object successNotification(HttpServletResponse response, HttpServletRequest request) throws AlipayApiException {
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Enumeration<String> parameterNames = request.getParameterNames();
        Map requestParams = request.getParameterMap();
        String appId = "";
        String msgMethod = "";
        System.out.println("requestParams: "+requestParams);
        while(parameterNames.hasMoreElements()){
            String paraName=(String)parameterNames.nextElement();
            System.out.println(paraName+": "+request.getParameter(paraName));
            System.out.println("paraName: "+paraName);
            System.out.println("value: "+request.getParameter(paraName));
            System.out.println("paraName: "+paraName.equals("app_id")+"+++++++++++");
            if(paraName.equals("app_id")){
                appId = request.getParameter(paraName);
            }
            if(paraName.equals("msg_method")){
                msgMethod = request.getParameter(paraName);
            }
        }
        String bizContent = request.getParameter("biz_content");
        JSONObject jsonObject = JSON.parseObject(bizContent);
        if(jsonObject!=null){
            appId = jsonObject.getString("mini_app_id");
        }
        msgMethod = request.getParameter("msg_method");
        log.info("appId:",appId);
        log.info("msgMethod:",msgMethod);
        System.out.println("appId: "+appId);
        System.out.println("msgMethod: "+msgMethod);
        if(!StringUtils.isEmpty(msgMethod)){
            InfoAuthAliAppDO infoAuthAliAppDO = infoAuthAliAppMapper.selectByAppId(appId);
            if(infoAuthAliAppDO!=null){
                if(msgMethod.equals("alipay.open.mini.version.audit.passed")){
                    infoAuthAliAppDO.setAppState("下架");
                    infoAuthAliAppDO.setOperateStatue("4");
                }else if(msgMethod.equals("alipay.open.mini.version.audit.rejected")){
                    infoAuthAliAppDO.setAppState("审核失败");
                    infoAuthAliAppDO.setOperateStatue("1");
                }
                infoAuthAliAppMapper.updateById(infoAuthAliAppDO);
            }
        }


       /* for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext ();) {
            String name =  ( String )iter.next();
            String[] values = (String[])requestParams.get(name);
            String valueStr="";
            for(int i = 0;i < values.length; i++){
                valueStr = (i== values.length-1)?valueStr+values[i]:valueStr+values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name,valueStr);
        }

        log.info("params:",params);
        //切记alipayPublicCertPath是支付宝公钥证书路径，请去open.alipay.com对应应用下载。
        //boolean AlipaySignature.rsaCertCheckV1(Map<String, String> params, String publicKeyCertPath, String charset,String signType)
        boolean flag = AlipaySignature.rsaCertCheckV1(params,"/var/javaApp/alipay/key20240210105508/alipayCertPublicKey_RSA2.crt","UTF-8","RSA2");
        log.info("flag:",flag);*/
        log.info("-----------------------------------------------------------------:");

        return params;
    }

    @Override
    public Object aliAuthNotification(String appAuthCode, String appId) {
        try {
            Map appAuthTokenByCode = getAppAuthTokenByCode("authorization_code", appAuthCode);
            Long authAppId = (Long)appAuthTokenByCode.get("auth_app_id");
            Long userId = (Long)appAuthTokenByCode.get("user_id");
            String appAuthToken = (String)appAuthTokenByCode.get("app_auth_token");
            System.out.println(appAuthTokenByCode);
            System.out.println(authAppId);
            System.out.println(userId);
            System.out.println(appAuthToken);
            InfoAuthAliAppCreateReqVO createReqVO = new InfoAuthAliAppCreateReqVO();
            createReqVO.setAuthTime(LocalDateTime.now());
            createReqVO.setAppAuthToken(appAuthToken);
            createReqVO.setAppId(authAppId);
            createReqVO.setAuthUserId(userId);
            createReqVO.setUsageQuantity(0l);
            infoAuthAliAppService.createInfoAuthAliApp(createReqVO);
            return createReqVO.getAppId();
        } catch (AlipayApiException e) {
            return "error";
        }
    }

    //查询版本详情
    public  String queryAppVersionList(String appId) throws AlipayApiException {
        CertAlipayRequest certAlipayRequest = Tool.getRequestTemplate();
        AlipayClient alipayClient = null;
        try {
            alipayClient = new DefaultAlipayClient(certAlipayRequest);
        } catch (AlipayApiException e1) {
            e1.printStackTrace();
        }

        InfoAuthAliAppDO infoAuthAliAppDO = infoAuthAliAppMapper.selectByAppId(appId);
        // 构造请求参数以调用接口
        AlipayOpenMiniVersionListQueryRequest   request = new AlipayOpenMiniVersionListQueryRequest();
        request.putOtherTextParam("app_auth_token", infoAuthAliAppDO.getAppAuthToken());
        AlipayOpenMiniVersionListQueryModel    model = new AlipayOpenMiniVersionListQueryModel  ();

        // 设置版本状态列表
        model.setVersionStatus("AUDITING");

        // 设置端参数
        model.setBundleId("com.alipay.alipaywallet");

        request.setBizModel(model);

        AlipayOpenMiniVersionListQueryResponse   response = alipayClient.certificateExecute(request);
        System.out.println(JSON.parseObject(response.getBody()));
        JSONObject jsonObject = JSON.parseObject(response.getBody());
        String alipayOpenMiniVersionListQueryResponse = jsonObject.getString("alipay_open_mini_version_list_query_response");
        JSONObject parse = JSON.parseObject(alipayOpenMiniVersionListQueryResponse);

        System.out.println(parse.getJSONArray("app_versions"));
        JSONArray appVersions = parse.getJSONArray("app_versions");
        if(appVersions==null){
            return null;
        }
        List<String> javaList = appVersions.toJavaList(String.class);

        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }
        return javaList.get(javaList.size()-1);
    }

    //查询版本详情
    public JSONObject queryAppVersionDetail(String appId,String version) throws AlipayApiException {
        CertAlipayRequest certAlipayRequest = Tool.getRequestTemplate();
        AlipayClient alipayClient = null;
        try {
            alipayClient = new DefaultAlipayClient(certAlipayRequest);
        } catch (AlipayApiException e1) {
            e1.printStackTrace();
        }


        InfoAuthAliAppDO infoAuthAliAppDO = infoAuthAliAppMapper.selectByAppId(appId);
        // 构造请求参数以调用接口
        AlipayOpenMiniVersionDetailQueryRequest request = new AlipayOpenMiniVersionDetailQueryRequest ();
        request.putOtherTextParam("app_auth_token", infoAuthAliAppDO.getAppAuthToken());
        AlipayOpenMiniVersionDetailQueryModel     model = new AlipayOpenMiniVersionDetailQueryModel   ();

// 设置小程序版本号
        model.setAppVersion(version);

        // 设置小程序端
        model.setBundleId("com.alipay.alipaywallet");

        request.setBizModel(model);

        AlipayOpenMiniVersionDetailQueryResponse  response = alipayClient.certificateExecute(request);
        System.out.println(JSON.parseObject(response.getBody()));
        JSONObject jsonObject = JSON.parseObject(response.getBody());
        String versionDetailQueryResponse = jsonObject.getString("alipay_open_mini_version_detail_query_response");
        JSONObject parse = JSON.parseObject(versionDetailQueryResponse);


        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }
        return parse;
    }


//    /**
//     * 用户信息解密
//     * @param data 前端传递的加密数据
//     * @return
//     * @throws Exception
//     */
//    private Map infoDecode(String data) throws Exception {
//        // 1. 获取验签和解密所需要的参数
//        Map<String, String> openapiResult =
//                JSON.parseObject(data, new TypeReference<Map<String, String>>() {}, Feature.OrderedField);
//
//        // 加签算法
//        String signType = "RSA2";
//        // 验签和解密用的字符集
//        String charset = "UTF-8";
//        // 支付宝公钥";
//        // 加密算法
//        String encryptType = "AES";
//        // 返回码
//        String code = "code";
//        String sign = openapiResult.get("sign");
//        String content = openapiResult.get("response");
//        // 是否加密
//        boolean isDataEncrypted = !content.startsWith("{");
//        // 是否验签通过
//        boolean signCheckPass = false;
//
//        // 2. 验签
//        String signContent = content;
//
//        /**
//         * 小程序对应的支付宝公钥（为扩展考虑建议用appId+signType做密钥存储隔离）
//         * 小程序对应的加解密密钥（为扩展考虑建议用appId+encryptType做密钥存储隔离）
//         */
//        String signVeriKey = aliConfig.getPublicKey();
//        String decryptKey = aliConfig.getDecryptKey();
//        // 如果是加密的报文则需要在密文的前后添加双引号
//        if (isDataEncrypted) {
//            signContent = "\"" + signContent + "\"";
//        }
//        try {
//            signCheckPass = AlipaySignature.rsaCheck(signContent, sign, signVeriKey, charset, signType);
//        } catch (AlipayApiException e) {
//            // 验签异常
//            log.error("支付宝解密用户信息 >>> 验签异常:{}",e.getMessage());
//        }
//        // 验签不通过（异常或者报文被篡改），终止流程（不需要做解密）
//        if (!signCheckPass) {
//            throw new AlipayApiException("验签失败");
//        }
//        // 3. 解密
//        String plainData = null;
//        if (isDataEncrypted) {
//            try {
//                plainData = AlipayEncrypt.decryptContent(content, encryptType, decryptKey, charset);
//            } catch (AlipayApiException e) {
//                // 解密异常, 记录日志
//                log.error("Decode Abnormal:{}",e.getMessage());
//                throw new AlipayApiException("解密异常");
//            }
//        } else {
//            plainData = content;
//        }
//        // 自定义转换 String 转 Map
//        Map map = BeanConvertUtils.objectToMap(JSON.parseObject(plainData));
//        if (map != null && AliConstant.SUCCEED_CODE.equals(map.get(code))) {
//            return map;
//        }else{
//            log.error("Decode Fail :{}",map);
//            throw new AlipayApiException("解密失败");
//        }
//    }




}
